package cn.java86.dao;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * @author oldliu
 * @since 1.0
 */
@Service
@Aspect//切面
public class UserLogger {
    //环绕式增强
    @Around("within(cn.java86.dao..*)")
    //@Before()
    //@After()
    public Object doLog(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("获得方法信息：");
        System.out.println(jp.getTarget()+":目标对象");
        System.out.println("方法名：" + jp.getSignature().getName());
        System.out.println("方法参数：" + Arrays.toString(jp.getArgs()));
        Object result = null;
        //update时候控制id>0
        if(jp.getSignature().getName().equals("update")){
            User u= (User) jp.getArgs()[0];
            if(u.getId()<=0){
                throw  new Exception("更新的id不能小于0");
                //抛了异常，后面的不执行
            }
        }
        //真的去执行dao方法
        long l = System.nanoTime();
        result = jp.proceed();//!!!!!!!
        long l2 = System.nanoTime();
        System.out.println("执行时间:"+(l2-l)+"纳秒");

        System.out.println("方法返回值：" + result);

        return result;
    }
}
